import 'dart:convert';

class NetPageData<T> {
  // late int current;
  // late int pages;
  // late int size;
  // late int total;
  late List<T>? list;
  late bool hasNextPage;

  NetPageData(
      {
      // this.current = 1,
      this.list = const [],
      // this.pages = 0,
      // this.size = 0,
      // this.total = 0,
      this.hasNextPage = false});

  factory NetPageData.fromJson(
      Map<String, dynamic> json, T Function(dynamic data) decoder) {
    return NetPageData(
      // current: asT<int>(json['current'], 1)!,
      list: (json['list'] is List)
          ? (json['list'] as List).map((e) => decoder(e)).toList()
          : const [],
      hasNextPage: asT<bool>(json['hasNextPage']) ?? false,
      // size: asT<int>(json['size'])!,
      // total: asT<int>(json['total'])!,
      // pages: asT<int>(json['pages'])!,
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    // data['current'] = this.current;
    // data['size'] = this.size;
    // data['total'] = this.total;
    // data['pages'] = this.pages;
    data['records'] = this.list;
    data['hasNextPage'] = this.hasNextPage;
    return data;
  }

// adaptList(List<T> list) {
//   if (this.current <= 1) {
//     list.assignAll(this.list ?? []);
//   } else {
//     list.addAll(this.list ?? []);
//   }
// }
}

T? asT<T>(dynamic value, [T? defaultValue]) {
  if (value is T) {
    return value;
  }
  if (value != null) {
    try {
      final String valueS = value.toString();
      if ('' is T) {
        return valueS as T;
      } else if (0 is T) {
        return int.parse(valueS) as T;
      } else if (0.0 is T) {
        return double.parse(valueS) as T;
      } else if (false is T) {
        return (valueS == '1' || valueS == 'true') as T;
      } else {
        return json.decode(value.toString()) as T?;
      }
    } catch (e) {
      // log('asT<$T>', error: e, stackTrace: s);
      if (0 is T) {
        return defaultValue ?? 0 as T;
      } else if (0.0 is T) {
        return defaultValue ?? 0.0 as T;
      } else if (false is T) {
        return defaultValue ?? false as T;
      }
    }
  } else {
    if ('' is T) {
      return defaultValue ?? "" as T;
    } else if (0 is T) {
      return defaultValue ?? 0 as T;
    } else if (0.0 is T) {
      return defaultValue ?? 0.0 as T;
    } else if (false is T) {
      return defaultValue ?? false as T;
    }
  }
  return defaultValue;
}
